package com.chs.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.chs.model.ShoppingCart;
import com.chs.model.dto.OrderDto;
import com.chs.service.OrderService;
import com.chs.service.ProductService;
import com.chs.service.ShoppingCartService;
import com.chs.service.UserService;
import com.chs.util.ResultUtil;
import com.chs.util.TokenUtil;

/**
 * (User)表控制层
 *
 * @author mopeiwen
 * @since 2020-06-10 10:49:15
 */
@RestController
@RequestMapping("/user")
public class ShoppingController {
	/**
	 * 服务对象
	 */
	@Resource
	private UserService userService;
	@Resource
	private ProductService productService;
	@Resource
	private ShoppingCartService shoppingCartService;
	@Resource
	private OrderService orderService;

	// 获得购物项列表(获得购物车)
	@GetMapping(value = "/sel-shop-cart")
	public ResultUtil selShopCart(@RequestParam(name = "pageNum", required = true, defaultValue = "1") int pageNum,
			@RequestParam(name = "pageSize", required = true, defaultValue = "4") int pageSize,
			HttpServletRequest request) {
		System.out.println(pageNum + " " + pageSize);
		return ResultUtil.ok("查询成功", shoppingCartService.selectAll(pageNum, pageSize,
				TokenUtil.getUserId(request.getHeader("Authorization"))));
	}

	// TODO 考虑商品的库存量
	// 添加购物项
	@PostMapping(value = "/add-shop-cart")
	public ResultUtil addShopCart(@Valid @RequestBody ShoppingCart shoppingCart) {
		System.out.println(shoppingCart);
		return ResultUtil.ok("添加成功", shoppingCartService.insert(shoppingCart));
	}

	// 删除购物项
	@PostMapping(value = "/del-shop-cart")
	public ResultUtil delShopCart(String scid) {
		return ResultUtil.ok("删除成功", shoppingCartService.deleteById(scid));
	}

	// 获得订单信息
	@GetMapping(value = "/get-orderinfo")
	public ResultUtil getOrderinfo(String pid_count, String scids) {
		System.out.println(pid_count + " " + scids);
		return ResultUtil.ok("查询成功", orderService.queryById(pid_count, scids));
	}

	// 确认订单信息 TODO 考虑下单减库存 不够回滚事务
	@PostMapping(value = "/ok-orderinfo")
	public ResultUtil okOrderinfo(@RequestBody OrderDto orderDto) {
		System.out.println(orderDto);
		return ResultUtil.ok("确认成功", orderService.insertOrder(orderDto));
	}

	// 支付成功修改订单记录 TODO 考虑支付调用接口 回调成功函数
	@PostMapping(value = "/order-pay")
	public ResultUtil orderPay(String oid) {
		System.out.println(oid);
		return ResultUtil.ok("修改成功", orderService.orderPay(oid));
	}

}
